<template>
  <el-dialog :title="title" :visible.sync="visible" @closed="clearData">
    <el-form :model="formData" :rules="rules" label-position="right" label-width="80px" ref="formData">
      <el-form-item label="用户名" prop="username">
        <el-input placeholder="用户名" v-model="formData.username" auto-complete="off"
                  :readonly="this.formData.userId !== ''"/>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input placeholder="昵称" v-model="formData.nickname"/>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload :action="uploadUrl" :file-list="photoList" list-type="picture-card" :headers="headers" :limit="1" :on-success="onSuccess" :on-exceed="onExceed" :before-upload="beforeUpload" ref="uploadImage">
          <i class="el-icon-plus"></i>
          <div slot="file" slot-scope="{file}">
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
            <span class="el-upload-list__item-actions">
              <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
              <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">可用</el-radio>
          <el-radio :label="2">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button type="warning" @click="visible = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="查看原图" :visible.sync="showImage" v-if="showImage" append-to-body>
      <img :src="baseImageSrc+formData.avatar" :alt="formData.avatar" width="100%" height="100%">
    </el-dialog>
  </el-dialog>
</template>

<script>
const initData = {
  userId: '',
  username: '',
  nickname: '',
  status: 1,
  avatar: ''
}
export default {
  name: 'UserinfoUpdate',
  data () {
    return {
      formData: { ...initData },
      rules: {
        username: [{
          required: true,
          message: '用户名不能为空',
          trigger: 'blur'
        }],
        nickname: [{
          required: true,
          message: '昵称不能为空',
          trigger: 'blur'
        }],
        avatar: [{
          required: true,
          message: '头像不能为空',
          trigger: 'blur'
        }]
      },
      title: '添加信息',
      visible: false,
      uploadUrl: process.env.VUE_APP_BASE_API + 'upload',
      baseImageSrc: process.env.VUE_APP_BASE_API + 'static/upload/',
      headers: {
        token: ''
      },
      photoList: [],
      showImage: false
    }
  },
  methods: {
    submitForm () {
      this.$refs.formData.validate(validate => {
        if (validate) {
          this.$http.post('user/update', this.formData).then(() => {
            this.$message.success(`${this.formData.userId ? '修改' : '添加'}成功`)
            this.visible = false
            this.$emit('closeWin')
          })
        }
      })
    },
    init (userId) {
      this.visible = true
      this.title = userId ? '修改信息' : '添加信息'
      if (userId) {
        this.$http.get(`user/info/${userId}`).then(data => {
          this.formData = { ...data.data }
          this.photoList.push({ name: data.data.avatar, url: `${process.env.VUE_APP_BASE_API}static/upload/${data.data.avatar}` })
        })
      }
    },
    clearData () {
      this.formData = { ...initData }
      this.photoList = []
      this.$refs.formData.resetFields()
    },
    handlePictureCardPreview () {
      this.showImage = true
    },
    handleRemove (file) {
      this.$confirm('确定删除图片吗?').then(() => {
        this.$refs.uploadImage.handleRemove(file)
        this.photoList.length = 0
        this.formData.avatar = ''
      })
    },
    onSuccess (res, file) {
      if (res.code === 200) {
        this.photoList.push({ name: res.data, url: `${process.env.VUE_APP_BASE_API}static/upload/${res.data}` })
        this.formData.avatar = res.data
      } else {
        this.$message.error('上传图片失败')
        this.$refs.uploadImage.handleRemove(file.raw)
        this.photoList.length = 0
        this.formData.avatar = ''
      }
    },
    onExceed () {
      this.$message.error('头像只能存在一张')
    },
    beforeUpload (file) {
      const isImg = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isImg) {
        this.$message.error('请选择正确的格式')
      }
      const isLt20M = file.size / 1024 / 1024 < 20
      if (!isLt20M) {
        this.$message.error('文件大小不能超过20MB')
      }
      return isImg && isLt20M
    }
  },
  created () {
    this.$nextTick(() => {
      this.headers.token = this.$cookies.get('token')
    })
  }
}
</script>

<style scoped>

</style>
